package com.zhichat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhichat.dao.AppVersionDao;
import com.zhichat.entity.AppVersionEntity;
import com.zhichat.infrastructure.Enums.AppVersionPublishStatusEnum;
import com.zhichat.infrastructure.config.OSSConfig;
import com.zhichat.infrastructure.constants.Constants;
import com.zhichat.infrastructure.exception.http.CommonException;
import com.zhichat.infrastructure.util.OSSClient;
import com.zhichat.infrastructure.util.Utils;
import com.zhichat.service.AppVersionService;
import com.zhichat.web.api.PageUtils;
import com.zhichat.web.dto.AdminAppVersionQueryDTO;
import com.zhichat.web.dto.AppVersionInfoAddOrUpdateDTO;
import com.zhichat.web.dto.AppVersionPublishDTO;
import com.zhichat.web.vo.AppVersionEntityVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@AllArgsConstructor
public class AppVersionServiceImpl extends ServiceImpl<AppVersionDao, AppVersionEntity> implements AppVersionService {

    private final OSSConfig ossConfig;

    @Override
    public PageUtils<AppVersionEntityVO> appList(AdminAppVersionQueryDTO dto) {
        String createTimeRange = dto.getCreateTimeRange();
        LambdaQueryWrapper<AppVersionEntity> queryWrapper = Wrappers.lambdaQuery(AppVersionEntity.class);
        // 前端传过来的 创建时间范围 做处理
        if (StringUtils.hasText(createTimeRange)) {
            if (!createTimeRange.contains(",")) {
                throw CommonException.PARAMETER_COMMON_EXCEPTION;
            }
            String[] strArr = createTimeRange.split(",");
            queryWrapper.between(AppVersionEntity::getCreateTime, Utils.concatTimeStart(strArr[0]), Utils.concatTimeEnd(strArr[1]));
        }
        queryWrapper.orderByDesc(AppVersionEntity::getId);
        Page<AppVersionEntity> page = baseMapper.selectPage(new Page<>(((dto.getPageNum() - 1) * dto.getPageSize()), dto.getPageSize()), queryWrapper);
        // 转换为VO
        List<AppVersionEntityVO> dataList = Lists.newArrayList();
        if (page.getSize() >= 0) {
            page.getRecords().forEach(x -> {
                AppVersionEntityVO vo = new AppVersionEntityVO();
                BeanUtils.copyProperties(x, vo);
                dataList.add(vo);
            });
        }
        PageUtils<AppVersionEntityVO> resData = new PageUtils<>(dataList, (int) page.getTotal(), dto.getPageSize(), dto.getPageNum());
        return resData;
    }

    @Override
    public boolean saveAppVersionInfo(AppVersionInfoAddOrUpdateDTO dto) {
        // 校验参数
        MultipartFile appVersionFile = dto.getAppVersionFile();
        if (appVersionFile.isEmpty()) {
            throw CommonException.PARAMETER_COMMON_EXCEPTION;
        }
        Integer id = dto.getId();
        String appVersion = dto.getVersionCode();
        // 校验版本号
        if (Objects.isNull(id)) {
            // (新增)校验版本号
            LambdaQueryWrapper<AppVersionEntity> queryWrapper = Wrappers.lambdaQuery(AppVersionEntity.class);
            queryWrapper.orderByDesc(AppVersionEntity::getId)
                    .last("limit 1");
            AppVersionEntity checkEntity = baseMapper.selectOne(queryWrapper);
            if (Objects.nonNull(checkEntity)) {
                int curVersion = Integer.parseInt(appVersion.replaceAll("\\.", ""));
                int maxVersion = Integer.parseInt(checkEntity.getVersionCode().replaceAll("\\.", ""));
                if (maxVersion >= curVersion) {
                    throw new CommonException("版本号必须大于当前最大版本号");
                }
            }
        } else {
            // (修改)校验版本号（id必须和versionCode一致，且唯一，versionCode不允许变更）
            // 不是未发布状态的数据，不允许修改数据
            LambdaQueryWrapper<AppVersionEntity> queryWrapper = Wrappers.lambdaQuery(AppVersionEntity.class);
            queryWrapper.eq(AppVersionEntity::getId, id)
                    .eq(AppVersionEntity::getVersionCode, appVersion);
            AppVersionEntity checkEntity = baseMapper.selectOne(queryWrapper);
            if (Objects.isNull(checkEntity) || !Objects.equals(AppVersionPublishStatusEnum.NOT_PUBLISHED.getCode(), checkEntity.getPublishStatus())) {
                throw CommonException.PARAMETER_COMMON_EXCEPTION;
            }
        }
        // 上传文件
        if (!OSSClient.uploadFile(appVersionFile, Constants.APP_VERSION_FILE_FOLDER,
                Constants.APP_PREFIX + appVersion.concat(Constants.APP_SUF_EXE), ossConfig, null)) {
            throw CommonException.FILE_OPERATE_COMMON_EXCEPTION;
        }
        // 保存/修改 数据
        AppVersionEntity appUpdateEntity = new AppVersionEntity();
        BeanUtils.copyProperties(dto, appUpdateEntity);
        return this.saveOrUpdate(appUpdateEntity);
    }

    @Override
    public boolean publishApp(AppVersionPublishDTO dto) {
        Integer publishStatus = dto.getPublishStatus();
        List<String> uIds = dto.getUIds();
        if (Objects.isNull(AppVersionPublishStatusEnum.getByCode(publishStatus)) || (CollectionUtils.isEmpty(uIds) && Objects.equals(publishStatus, AppVersionPublishStatusEnum.PUBLISHED_ANY.getCode()))) {
            throw CommonException.PARAMETER_COMMON_EXCEPTION;
        }
        AppVersionEntity appVersionEntity = new AppVersionEntity();
        BeanUtils.copyProperties(dto, appVersionEntity);
        appVersionEntity.setTestUserId(CollectionUtils.isEmpty(uIds) ? null : String.join(",", uIds));
        int i = baseMapper.updateById(appVersionEntity);
        return 1 == i;
    }
}